/**
 * 项目版本历史模型
 *
 * Created by snowingsea on 2020/05/09.
 */
const mongoose = require('mongoose');
const ProjectVersionHistory = require('./mongo/project-version-history');
const Filter = require('./mongo/filter');
const { eventHub, eventKind } = require('./event-hub');

/**
 * 项目历史状态
 * @type {Object}
 */
const historyKind = {
  addFile: 1, // 添加文件
  deleteFile: 2, // 删除文件
  replaceFile: 3, // 替换文件
  editFile: 4, // 编辑文件
  updateSource: 5, // 重新上传源代码
};

/**
 * 获取项目版本历史json信息
 * @param {ProjectVersionHistory} versionHistory 项目历史信息
 * @return {Object}
 */
function getJson(versionHistory) {
  const historyId = versionHistory._id; // eslint-disable-line no-underscore-dangle
  return {
    historyId,
    versionId: versionHistory.versionId,
    kind: versionHistory.kind,
    createAt: historyId.getTimestamp().getTime(),
    details: versionHistory.details,
  };
}

/**
 * 获取项目版本历史信息
 * @param {String} historyId 项目历史id
 * @return {Promise}
 */
function getHistory(historyId) {
  return ProjectVersionHistory.findOne({ _id: mongoose.Types.ObjectId(historyId) });
}

/**
 * 筛选历史列表
 * @param {Object} pagination 分页信息
 * @param {Object} options 用户筛选项
 * @return {Promise}
 */
function filter(pagination = {}, options = {}) {
  const { sortBy } = pagination;
  if (!sortBy || (sortBy === 'historyId') || (sortBy === 'createAt')) {
    pagination.sortBy = '_id';
  }
  return Filter.filter(ProjectVersionHistory, pagination, options);
}

/**
 * 项目版本历史数目
 * @param {Object} options 用户筛选项
 * @return {Promise}
 */
function getCount(options = {}) {
  return ProjectVersionHistory.countDocuments(options);
}

/**
 * 添加历史信息
 * @param {String} versionId 项目版本id
 * @param {Number} kind 历史类型
 * @param {Object} details 详细信息
 * @return {Promise}
 */
function addHistory(versionId, kind, details) {
  const history = new ProjectVersionHistory({
    versionId: mongoose.Types.ObjectId(versionId),
    kind,
    details,
  });
  return history.save();
}

eventHub.on(eventKind.EVENT_VERSION_REMOVE, (versionId) => ProjectVersionHistory.deleteMany({ versionId: mongoose.Types.ObjectId(versionId) }));

/**
 * Export model definition object.
 */
module.exports = {
  kind: historyKind,

  getJson,

  getHistory,
  filter,
  getCount,

  addHistory,
};
